﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Gmantis.Controls
{
    [TemplateVisualState(Name = "Highlighted", GroupName = "HighlightedStates"), TemplateVisualState(Name = "Closed", GroupName = "OpenedStates"), TemplatePart(Name = "SubItemsPopup", Type = typeof(Popup)), TemplateVisualState(Name = "NonHighlighted", GroupName = "HighlightedStates"), TemplatePart(Name = "ExpandIcon", Type = typeof(Shape)), TemplatePart(Name = "MenuIcon", Type = typeof(ContentControl)), TemplatePart(Name = "CheckIcon", Type = typeof(FrameworkElement)), TemplatePart(Name = "HeaderPanel", Type = typeof(Grid)), TemplatePart(Name = "SubItemsPresenter", Type = typeof(ItemsPresenter)), TemplateVisualState(Name = "Opened", GroupName = "OpenedStates")]
    public class MenuItem : HierarchicalPresenter
    {
        // Fields
        internal FrameworkElement _elementCheckIcon;
        internal Shape _elementExpandIcon;
        internal Grid _elementHeaderPanel;
        internal ContentControl _elementMenuIcon;
        internal Popup _elementSubItemsPopup;
        internal ItemsPresenter _elementSubItemsPresenter;
        internal bool _isLoaded;
        internal bool _templateLoadedProperly;
        internal const string CheckIconElementName = "CheckIcon";
        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnCommandParameterPropertyChanged)));
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnCommandPropertyChanged)));
        public static readonly DependencyProperty DisabledCuesVisibilityProperty = DependencyProperty.Register("DisabledCuesVisibility", typeof(Visibility), typeof(MenuItem), new PropertyMetadata(Visibility.Visible));
        internal const string ExpandIconElementName = "ExpandIcon";
        public static readonly DependencyProperty FocusCuesVisibilityProperty = DependencyProperty.Register("FocusCuesVisibility", typeof(Visibility), typeof(MenuItem), new PropertyMetadata(Visibility.Visible));
        public static readonly DependencyProperty GroupNameProperty = DependencyProperty.Register("GroupName", typeof(string), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnGroupNamePropertyChanged)));
        public static readonly DependencyProperty HeaderBackgroundProperty = DependencyProperty.Register("HeaderBackground", typeof(Brush), typeof(MenuItem), null);
        public static readonly DependencyProperty HeaderForegroundProperty = DependencyProperty.Register("HeaderForeground", typeof(Brush), typeof(MenuItem), null);
        internal const string HeaderPanelElementName = "HeaderPanel";
        public static readonly DependencyProperty HighlightedBackgroundProperty = DependencyProperty.Register("HighlightedBackground", typeof(Brush), typeof(MenuItem), null);
        public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(object), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnIconPropertyChanged)));
        public static readonly DependencyProperty IsCheckableProperty = DependencyProperty.Register("IsCheckable", typeof(bool), typeof(MenuItem), null);
        public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnIsCheckedPropertyChanged)));
        public static readonly DependencyProperty IsHighlightedProperty = DependencyProperty.Register("IsHighlighted", typeof(bool), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnIsHighlightedPropertyChanged)));
        public static readonly DependencyProperty IsSubmenuOpenProperty = DependencyProperty.Register("IsSubmenuOpen", typeof(bool), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnIsSubmenuOpenPropertyChanged)));
        internal static readonly DependencyProperty IsSubmenuOpenVisualProperty = DependencyProperty.Register("IsSubmenuOpenVisual", typeof(bool), typeof(MenuItem), new PropertyMetadata(new PropertyChangedCallback(MenuItem.OnIsSubmenuOpenVisualPropertyChanged)));
        internal const string MenuIconElementName = "MenuIcon";
        public static readonly DependencyProperty OpenedBackgroundProperty = DependencyProperty.Register("OpenedBackground", typeof(Brush), typeof(MenuItem), null);
        internal const string SubItemsPopupElementName = "SubItemsPopup";
        internal const string SubItemsPresenterElementName = "SubItemsPresenter";
        public static readonly DependencyProperty SubMenuMaxHeightProperty = DependencyProperty.Register("SubMenuMaxHeight", typeof(double), typeof(MenuItem), new PropertyMetadata((double)1.0 / (double)0.0));
        public static readonly DependencyProperty TextAlignmentProperty = DependencyProperty.Register("TextAlignment", typeof(TextAlignment), typeof(MenuItem), null);
        public static readonly DependencyProperty TextDecorationsProperty = DependencyProperty.Register("TextDecorations", typeof(TextDecorationCollection), typeof(MenuItem), null);
        public static readonly DependencyProperty TextWrappingProperty = DependencyProperty.Register("TextWrapping", typeof(TextWrapping), typeof(MenuItem), null);

        // Events
        public event EventHandler<SourcedEventArgs> Checked;

        public event EventHandler<SourcedEventArgs> Click;

        public event EventHandler<SourcedEventArgs> SubmenuClosed;

        public event EventHandler<CancelSourceEventArgs> SubmenuClosing;

        public event EventHandler<SourcedEventArgs> SubmenuOpened;

        public event EventHandler<CancelSourceEventArgs> SubmenuOpening;

        public event EventHandler<SourcedEventArgs> Unchecked;

        // Methods
        public MenuItem()
        {
            RoutedEventHandler handler = null;
            base.DefaultStyleKey = typeof(MenuItem);
            if (handler == null)
            {
                handler = delegate(object param0, System.Windows.RoutedEventArgs param1)
                {
                    this.ChangeVisualStateOpened(false);
                    this.ChangeVisualStateHighlighted(false);
                };
            }
            base.Loaded += handler;
            this.SetCustomDefaultValues();
        }

        protected void ChangeVisualStateHighlighted(bool useTransitions)
        {
            if (!this.IsHighlighted)
            {
                VisualStateHelper.GoToState(this, "NonHighlighted", useTransitions);
            }
            if (this.IsHighlighted)
            {
                VisualStateHelper.GoToState(this, "Highlighted", useTransitions);
            }
        }

        protected void ChangeVisualStateOpened(bool useTransitions)
        {
            if (!this.IsSubmenuOpenVisual)
            {
                VisualStateHelper.GoToState(this, "Closed", useTransitions);
            }
            if (this.IsSubmenuOpenVisual)
            {
                VisualStateHelper.GoToState(this, "Opened", useTransitions);
            }
        }

        protected override void ClearContainerForItemOverride(DependencyObject element, object item)
        {
            base.ClearContainerForItemOverride(element, item);
            MenuItem item2 = element as MenuItem;
            if ((item2 != null) && !PlatformIndependent.IsInDesignMode(this))
            {
                item2.UpdateGroupChecks(item2.GroupName, string.Empty);
            }
        }

        private void Close()
        {
            foreach (MenuItem item in this.MenuItems)
            {
                item.IsHighlighted = false;
                item.IsMouseOver = false;
            }
            if (base.HasItems && this._isLoaded)
            {
                this._elementSubItemsPopup.IsOpen = false;
            }
            this.Menu.HideAutoCloseAreas();
        }

        internal void CollapseSibling()
        {
            foreach (MenuItem item in base.GetParentContainers<MenuItem>())
            {
                if (item != this)
                {
                    CancelSourceEventArgs e = new CancelSourceEventArgs
                    {
                        Source = item,
                        Cancel = false
                    };
                    item.OnSubmenuClosing(e);
                }
            }
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new MenuItem();
        }

        private MenuItem GetFirstLevelMenu(MenuItem currentItem)
        {
            if (currentItem.IsFirstLevel)
            {
                return currentItem;
            }
            return this.GetFirstLevelMenu(currentItem.ParentItem);
        }

        private DataTemplate GetItemDataTemplate(MenuItem menuItem, object dataItem)
        {
            DataTemplate itemTemplate = null;
            if (base.ItemTemplateSelector != null)
            {
                itemTemplate = base.ItemTemplateSelector.SelectTemplate(dataItem, menuItem);
            }
            if (base.ItemTemplate != null)
            {
                itemTemplate = base.ItemTemplate;
            }
            return itemTemplate;
        }

        private T GetTemplateChild<T>(string childName, bool required, ref string errors) where T : class
        {
            DependencyObject templateChild = base.GetTemplateChild(childName);
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "template part", childName, templateChild, required, ref errors);
            return (templateChild as T);
        }

        private static Storyboard GetTemplateChildResource(FrameworkElement root, string resourceName, bool required, ref string errors)
        {
            return GetTemplateChildResource<Storyboard>(root, resourceName, required, ref errors);
        }

        private static T GetTemplateChildResource<T>(FrameworkElement root, string resourceName, bool required, ref string errors) where T : class
        {
            object child = root.Resources[resourceName];
            ApplyTemplateHelper.VerifyTemplateChild(typeof(T), "resource", resourceName, child, required, ref errors);
            return (child as T);
        }

        internal MenuItem HandleKey(Key e)
        {
            return this.MenuBehavior.HandleKey(e);
        }

        private void InitializeHeaderPanelPart()
        {
            this._elementHeaderPanel.MouseEnter += new MouseEventHandler(this.OnMouseEnter);
            this._elementHeaderPanel.MouseLeave += new MouseEventHandler(this.OnMouseLeave);
            MouseHelper helper = new MouseHelper(this._elementHeaderPanel);
            helper.MouseClick += new MouseEventHandler(this.OnMouseClick);
        }

        private void InitializeMenuIconPart()
        {
            this._elementMenuIcon.Content = this.Icon;
        }

        private void InitializeSubItemsPopupPart()
        {
            EventHandler handler = null;
            try
            {
                if (this.Menu.DetectBoundaries)
                {
                    this.MenuBehavior.MakeRelative(this._elementSubItemsPopup);
                }
                if (handler == null)
                {
                    handler = delegate(object s, EventArgs e)
                    {
                        if (this.IsSubmenuOpen && base.HasItems)
                        {
                            this.MenuBehavior.ShowSubItems();
                        }
                    };
                }
                this._elementSubItemsPopup.LayoutUpdated += handler;
            }
            catch
            {
            }
        }

        protected override bool IsItemItsOwnContainerOverride(object item)
        {
            return ((item is MenuItem) || (item is Separator));
        }

        private void OnAfterApplyTemplate()
        {
            if (this._templateLoadedProperly)
            {
                if (this._elementExpandIcon != null)
                {
                    this._elementExpandIcon.Visibility = base.HasItems ? Visibility.Visible : Visibility.Collapsed;
                }
                if (this._elementCheckIcon != null)
                {
                    this._elementCheckIcon.Visibility = (this.IsCheckable && this.IsChecked) ? Visibility.Visible : Visibility.Collapsed;
                }
                if (this.IsSubmenuOpen)
                {
                    this.OnIsSubmenuOpenChanged(false);
                }
                if (this.IsHighlighted)
                {
                    this.OnIsHighlightedChanged(false);
                }
            }
        }

        public override void OnApplyTemplate()
        {
            this.OnBeforeApplyTemplate();
            string errors = string.Empty;
            base.OnApplyTemplate();
            this._isLoaded = true;
            this._elementHeaderPanel = this.GetTemplateChild<Grid>("HeaderPanel", true, ref errors);
            if (this._elementHeaderPanel != null)
            {
                this.InitializeHeaderPanelPart();
            }
            this._elementExpandIcon = this.GetTemplateChild<Shape>("ExpandIcon", false, ref errors);
            this._elementMenuIcon = this.GetTemplateChild<ContentControl>("MenuIcon", false, ref errors);
            if (this._elementMenuIcon != null)
            {
                this.InitializeMenuIconPart();
            }
            this._elementCheckIcon = this.GetTemplateChild<FrameworkElement>("CheckIcon", false, ref errors);
            this._elementSubItemsPopup = this.GetTemplateChild<Popup>("SubItemsPopup", true, ref errors);
            if (this._elementSubItemsPopup != null)
            {
                this.InitializeSubItemsPopupPart();
            }
            this._elementSubItemsPresenter = this.GetTemplateChild<ItemsPresenter>("SubItemsPresenter", true, ref errors);
            if (!string.IsNullOrEmpty(errors))
            {
                this._templateLoadedProperly = false;
                this._isLoaded = false;
                if ((base.Template != null) && !PlatformIndependent.IsInDesignMode(this))
                {
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Template cannot be applied to MenuItem.\nDetails: {0}", new object[] { errors }));
                }
            }
            else
            {
                this._templateLoadedProperly = true;
                this.ChangeVisualStateOpened(false);
                this.ChangeVisualStateHighlighted(false);
                this.OnAfterApplyTemplate();
            }
        }

        private void OnBeforeApplyTemplate()
        {
            if (this._elementMenuIcon != null)
            {
                this._elementMenuIcon.Content = null;
            }
        }

        protected virtual void OnChecked(SourcedEventArgs e)
        {
            if (this.Checked != null)
            {
                this.Checked(this, e);
            }
            this.Menu.OnItemChecked(e);
        }

        protected virtual void OnClick(SourcedEventArgs e)
        {
            if (this.Click != null)
            {
                this.Click(this, e);
            }
            this.Menu.OnItemClick(e);
            if ((this.Command != null) && this.Command.CanExecute(this.CommandParameter))
            {
                this.Command.Execute(this.CommandParameter);
            }
        }

        private void OnCommandChanged(ICommand oldValue)
        {
            if (oldValue != null)
            {
                oldValue.CanExecuteChanged -= new EventHandler(this.RefreshCommandCanExecute);
            }
            if (this.Command != null)
            {
                this.Command.CanExecuteChanged += new EventHandler(this.RefreshCommandCanExecute);
            }
            this.RefreshCommandCanExecute(this, EventArgs.Empty);
        }

        private void OnCommandParameterChanged(object oldValue)
        {
            this.RefreshCommandCanExecute(this, EventArgs.Empty);
        }

        private static void OnCommandParameterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            object oldValue = e.OldValue;
            item.OnCommandParameterChanged(oldValue);
        }

        private static void OnCommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            ICommand oldValue = (ICommand)e.OldValue;
            item.OnCommandChanged(oldValue);
        }

        private void OnGroupNameChanged(string oldGroup)
        {
            if (this._isLoaded)
            {
                this.UpdateGroupChecks(oldGroup, this.GroupName);
            }
        }

        private static void OnGroupNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            string oldValue = (string)e.OldValue;
            item.OnGroupNameChanged(oldValue);
        }

        private void OnIconChanged(object oldValue)
        {
            if (this._elementMenuIcon != null)
            {
                this._elementMenuIcon.Content = this.Icon;
            }
        }

        private static void OnIconPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            object oldValue = e.OldValue;
            item.OnIconChanged(oldValue);
        }

        private void OnIsCheckedChanged(bool oldValue)
        {
            if (this.IsCheckable && (this._elementCheckIcon != null))
            {
                if (this.IsChecked)
                {
                    this._elementCheckIcon.Visibility = Visibility.Visible;
                    SourcedEventArgs e = new SourcedEventArgs
                    {
                        Source = this
                    };
                    this.OnChecked(e);
                }
                else
                {
                    this._elementCheckIcon.Visibility = Visibility.Collapsed;
                    SourcedEventArgs args2 = new SourcedEventArgs
                    {
                        Source = this
                    };
                    this.OnUnchecked(args2);
                }
            }
            Menu rootPresenter = base.RootPresenter as Menu;
            if (rootPresenter != null)
            {
                rootPresenter.UpdateGroupChecks(this);
            }
        }

        private static void OnIsCheckedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            bool oldValue = (bool)e.OldValue;
            item.OnIsCheckedChanged(oldValue);
        }

        private void OnIsHighlightedChanged(bool oldValue)
        {
            if ((this._isLoaded && !oldValue) && this.IsHighlighted)
            {
                this.Menu.HighlightedItem = this;
            }
        }

        private static void OnIsHighlightedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            bool oldValue = (bool)e.OldValue;
            item.OnIsHighlightedChanged(oldValue);
            item.ChangeVisualStateHighlighted(true);
        }

        private void OnIsSubmenuOpenChanged(bool oldValue)
        {
            if (this._isLoaded)
            {
                this.IsSubmenuOpenVisual = base.ForceMouseOver = this.IsSubmenuOpen && base.HasItems;
                if (this.IsSubmenuOpen)
                {
                    this.Open();
                    SourcedEventArgs e = new SourcedEventArgs
                    {
                        Source = this
                    };
                    this.OnSubmenuOpened(e);
                }
                else
                {
                    this.Close();
                    SourcedEventArgs args2 = new SourcedEventArgs
                    {
                        Source = this
                    };
                    this.OnSubmenuClosed(args2);
                }
            }
        }

        private static void OnIsSubmenuOpenPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MenuItem item = d as MenuItem;
            bool oldValue = (bool)e.OldValue;
            item.OnIsSubmenuOpenChanged(oldValue);
        }

        private static void OnIsSubmenuOpenVisualPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as MenuItem).ChangeVisualStateOpened(true);
        }

        protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
        {
            base.OnItemsChanged(e);
            IList list = (e.Action == NotifyCollectionChangedAction.Reset) ? base.Items : e.NewItems;
            if (list != null)
            {
                Menu rootPresenter = base.RootPresenter as Menu;
                foreach (object obj2 in list)
                {
                    HierarchicalPresenter presenter = obj2 as HierarchicalPresenter;
                    if (presenter != null)
                    {
                        presenter.InitializePresenter(null, this);
                    }
                    MenuItem item = obj2 as MenuItem;
                    if ((item != null) && (rootPresenter != null))
                    {
                        rootPresenter.MoveToGroupName(item.GroupName, item.GroupName, item);
                        rootPresenter.UpdateGroupChecks(item);
                        foreach (MenuItem item2 in item.ToList<MenuItem>())
                        {
                            rootPresenter.MoveToGroupName(item2.GroupName, item2.GroupName, item2);
                            rootPresenter.UpdateGroupChecks(item2);
                        }
                    }
                }
            }
        }

        protected internal virtual void OnMouseClick(object sender, MouseEventArgs e)
        {
            if (this.IsCheckable)
            {
                this.IsChecked = !this.IsChecked;
            }
            this.MenuBehavior.OnMouseClick(sender, e);
            this.Menu.Focus();
            SourcedEventArgs args = new SourcedEventArgs
            {
                Source = this
            };
            this.OnClick(args);
        }

        protected internal virtual void OnMouseEnter(object sender, MouseEventArgs e)
        {
            base.IsMouseOver = true;
            if (this.MenuBehavior != null)
            {
                this.MenuBehavior.OnMouseEnter(sender, e);
                this.IsHighlighted = base.IsMouseOver;
            }
        }

        protected internal virtual void OnMouseLeave(object sender, MouseEventArgs e)
        {
            if (this.MenuBehavior != null)
            {
                this.MenuBehavior.OnMouseLeave(sender, e);
                this.IsHighlighted = base.IsMouseOver;
            }
        }

        protected override void OnMouseRightButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseRightButtonDown(e);
            e.Handled = true;
        }

        protected virtual void OnSubmenuClosed(SourcedEventArgs e)
        {
            if (this.SubmenuClosed != null)
            {
                this.SubmenuClosed(this, e);
            }
            this.Menu.OnItemClosed(e);
        }

        protected internal virtual void OnSubmenuClosing(CancelSourceEventArgs e)
        {
            if (this.IsSubmenuOpen)
            {
                bool flag = false;
                foreach (MenuItem item in this.MenuItems)
                {
                    CancelSourceEventArgs args = new CancelSourceEventArgs
                    {
                        Source = item,
                        Cancel = false
                    };
                    item.OnSubmenuClosing(args);
                    flag = flag || args.Cancel;
                }
                e.Cancel = flag;
                if (this.SubmenuClosing != null)
                {
                    this.SubmenuClosing(this, e);
                }
                this.Menu.OnItemClosing(e);
                if (!e.Cancel)
                {
                    this.IsSubmenuOpen = false;
                }
            }
        }

        protected virtual void OnSubmenuOpened(SourcedEventArgs e)
        {
            if (this.SubmenuOpened != null)
            {
                this.SubmenuOpened(this, e);
            }
            this.Menu.OnItemOpened(e);
        }

        protected internal virtual void OnSubmenuOpening(CancelSourceEventArgs e)
        {
            if (!this.IsSubmenuOpen)
            {
                if (this.SubmenuOpening != null)
                {
                    this.SubmenuOpening(this, e);
                }
                this.Menu.OnItemOpening(e);
                if (!e.Cancel)
                {
                    this.IsSubmenuOpen = true;
                }
                ContentControl templateChild = base.GetTemplateChild("_contentControl") as ContentControl;
                if (((templateChild != null) && (templateChild.GetBindingExpression(FrameworkElement.MaxHeightProperty) == null)) && (templateChild.MaxHeight > this.SubMenuMaxHeight))
                {
                    templateChild.Height = this.SubMenuMaxHeight;
                }
            }
        }

        protected virtual void OnUnchecked(SourcedEventArgs e)
        {
            if (this.Unchecked != null)
            {
                this.Unchecked(this, e);
            }
            this.Menu.OnItemUnchecked(e);
        }

        private void Open()
        {
            this.CollapseSibling();
            if (base.HasItems)
            {
                if (this.ParentItem != null)
                {
                    CancelSourceEventArgs e = new CancelSourceEventArgs
                    {
                        Source = this.ParentItem,
                        Cancel = false
                    };
                    this.ParentItem.OnSubmenuOpening(e);
                }
                this.Menu.Focus();
                this.Menu.ShowAutoCloseAreas();
                if (this._isLoaded && !this._elementSubItemsPopup.IsOpen)
                {
                    this.MenuBehavior.ShowSubItems();
                }
            }
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            MenuItem menuItem = element as MenuItem;
            if ((menuItem != null) && !PlatformIndependent.IsInDesignMode(this))
            {
                if (menuItem != item)
                {
                    DataTemplate itemDataTemplate = this.GetItemDataTemplate(menuItem, item);
                    if (itemDataTemplate is HierarchicalDataTemplate)
                    {
                        HierarchicalDataTemplate template2 = itemDataTemplate as HierarchicalDataTemplate;
                        menuItem.SetBinding(ItemsControl.ItemsSourceProperty, template2.ItemsSource);
                        if (template2.ItemTemplate == null)
                        {
                            menuItem.ItemTemplate = base.ItemTemplate;
                        }
                        else
                        {
                            menuItem.ItemTemplate = template2.ItemTemplate;
                        }
                    }
                }
                menuItem.IsFirstLevel = false;
                if ((menuItem.Style == null) && (this.Menu.NonFirstLevelStyle != null))
                {
                    menuItem.Style = this.Menu.NonFirstLevelStyle;
                }
                base.PrepareContainerForItemOverride(element, item);
                if (this.MenuBehavior is ContextMenuItemBehavior)
                {
                    menuItem.MenuBehavior = new ContextMenuItemBehavior(menuItem);
                }
                else
                {
                    menuItem.MenuBehavior = new MenuItemNonFirstLevel(menuItem);
                }
                menuItem.SetBinding<MenuItem>(Control.FontFamilyProperty, this, m => m.FontFamily);
                menuItem.SetBinding<MenuItem>(Control.FontSizeProperty, this, m => m.FontSize);
                menuItem.SetBinding<MenuItem>(Control.FontStretchProperty, this, m => m.FontStretch);
                menuItem.SetBinding<MenuItem>(Control.FontStyleProperty, this, m => m.FontStyle);
                menuItem.SetBinding<MenuItem>(Control.FontWeightProperty, this, m => m.FontWeight);
                menuItem.SetBinding<MenuItem>(Control.BackgroundProperty, this, m => m.Background);
                menuItem.SetBinding<MenuItem>(Control.ForegroundProperty, this, m => m.Foreground);
                menuItem.SetBinding<MenuItem>(HeaderBackgroundProperty, this, m => m.Background);
                menuItem.SetBinding<MenuItem>(HeaderForegroundProperty, this, m => m.Foreground);
                menuItem.SetBinding<MenuItem>(Control.BorderBrushProperty, this, m => m.BorderBrush);
                menuItem.SetBinding<MenuItem>(UIElement.OpacityProperty, this, m => m.Opacity);
                menuItem.SetBinding<MenuItem>(HighlightedBackgroundProperty, this, m => m.HighlightedBackground);
                menuItem.SetBinding<MenuItem>(OpenedBackgroundProperty, this, m => m.OpenedBackground);
                menuItem.SetBinding<MenuItem>(SubMenuMaxHeightProperty, this, m => m.SubMenuMaxHeight);
                menuItem.SetBinding<MenuItem>(Control.IsEnabledProperty, this, m => m.IsEnabled);
                menuItem.UpdateGroupChecks(string.Empty, menuItem.GroupName);
            }
            Separator target = item as Separator;
            if (target != null)
            {
                target.Orientation = Orientation.Horizontal;
                target.Style = this.Menu.SeparatorStyle;
                target.SetBinding<MenuItem>(Control.BackgroundProperty, this, m => m.Background);
            }
        }

        private void RefreshCommandCanExecute(object sender, EventArgs e)
        {
            base.IsEnabled = (this.Command == null) || this.Command.CanExecute(this.CommandParameter);
        }

        private void SetCustomDefaultValues()
        {
            base.MouseEnter += new MouseEventHandler(this.OnMouseEnter);
            base.MouseLeave += (s, e) => base.IsMouseOver = false;
            base.IsTabStop = false;
        }

        internal void UpdateGroupChecks(string oldGroup, string newGroup)
        {
            this.Menu.MoveToGroupName(oldGroup, newGroup, this);
            this.Menu.UpdateGroupChecks(this);
        }

        // Properties
        internal Rect Bounds
        {
            get
            {
                FrameworkElement menu = this.Menu;
                Point point = this._elementHeaderPanel.GTransformToVisual(menu).Transform(new Point(0.0, 0.0));
                return new Rect(point.X, point.Y, this._elementHeaderPanel.ActualWidth, this._elementHeaderPanel.ActualHeight);
            }
        }

        public ICommand Command
        {
            get { return (ICommand)GetValue(CommandProperty); }
            set { SetValue(CommandProperty, value); }
        }

        public object CommandParameter
        {
            get { return GetValue(CommandParameterProperty); }
            set { SetValue(CommandParameterProperty, value); }
        }

        public Visibility DisabledCuesVisibility
        {
            get { return (Visibility)GetValue(DisabledCuesVisibilityProperty); }
            set { SetValue(DisabledCuesVisibilityProperty, value); }
        }

        internal MenuItem FirstLevelMenu
        {
            get
            {
                return this.GetFirstLevelMenu(this);
            }
        }

        public Visibility FocusCuesVisibility
        {
            get { return (Visibility)GetValue(FocusCuesVisibilityProperty); }
            set { SetValue(FocusCuesVisibilityProperty, value); }
        }

        public string GroupName
        {
            get { return (string)GetValue(GroupNameProperty); }
            set { SetValue(GroupNameProperty, value); }
        }

        public Brush HeaderBackground
        {
            get { return (Brush)GetValue(HeaderBackgroundProperty); }
            set { SetValue(HeaderBackgroundProperty, value); }
        }

        public Brush HeaderForeground
        {
            get { return (Brush)GetValue(HeaderForegroundProperty); }
            set { SetValue(HeaderForegroundProperty, value); }
        }

        public Brush HighlightedBackground
        {
            get { return (Brush)GetValue(HighlightedBackgroundProperty); }
            set { SetValue(HighlightedBackgroundProperty, value); }
        }

        public object Icon
        {
            get { return GetValue(IconProperty); }
            set { SetValue(IconProperty, value); }
        }

        public int Index
        {
            get
            {
                return GetParentContainers<MenuItem>().IndexOf(this);
            }
        }

        public bool IsCheckable
        {
            get { return (bool)GetValue(IsCheckableProperty); }
            set { SetValue(IsCheckableProperty, value); }
        }

        public bool IsChecked
        {
            get { return (bool)GetValue(IsCheckedProperty); }
            set { SetValue(IsCheckedProperty, value); }
        }

        internal bool IsFirstLevel { get; set; }

        public bool IsHighlighted
        {
            get { return (bool)GetValue(IsHighlightedProperty); }
            set { SetValue(IsHighlightedProperty, value); }
        }

        public bool IsSubmenuOpen
        {
            get { return (bool)GetValue(IsSubmenuOpenProperty); }
            set { SetValue(IsSubmenuOpenProperty, value); }
        }

        internal bool IsSubmenuOpenVisual
        {
            get { return (bool)GetValue(IsSubmenuOpenVisualProperty); }
            set { SetValue(IsSubmenuOpenVisualProperty, value); }
        }

        public Menu Menu
        {
            get
            {
                if (base.RootPresenter == null)
                {
                    throw new InvalidOperationException("MenuItem must be initialized in order to perform this action");
                }
                if (!(base.RootPresenter is Menu))
                {
                    throw new InvalidOperationException("MenuItem must be child of a C1Menu control");
                }
                return (Menu)base.RootPresenter;
            }
        }

        internal MenuItemBehavior MenuBehavior { get; set; }

        internal IList<MenuItem> MenuItems
        {
            get
            {
                IList<MenuItem> list = new List<MenuItem>();
                foreach (object obj2 in base.Items)
                {
                    MenuItem container = base.GetContainer(obj2) as MenuItem;
                    if (container != null)
                    {
                        list.Add(container);
                    }
                }
                return list;
            }
        }

        public Brush OpenedBackground
        {
            get { return (Brush)GetValue(OpenedBackgroundProperty); }
            set { SetValue(OpenedBackgroundProperty, value); }
        }

        public MenuItem ParentItem
        {
            get
            {
                if (base.ParentPresenter == null)
                {
                    throw new InvalidOperationException("MenuItem must be initialized in order to perform this action");
                }
                return (base.ParentPresenter as MenuItem);
            }
        }

        public double SubMenuMaxHeight
        {
            get { return (double)GetValue(SubMenuMaxHeightProperty); }
            set { SetValue(SubMenuMaxHeightProperty, value); }
        }

        public TextAlignment TextAlignment
        {
            get { return (TextAlignment)GetValue(TextAlignmentProperty); }
            set { SetValue(TextAlignmentProperty, value); }
        }

        public TextDecorationCollection TextDecorations
        {
            get { return (TextDecorationCollection)GetValue(TextDecorationsProperty); }
            set { SetValue(TextDecorationsProperty, value); }
        }

        public TextWrapping TextWrapping
        {
            get { return (TextWrapping)GetValue(TextWrappingProperty); }
            set { SetValue(TextWrappingProperty, value); }
        }
    }
}
